<!DOCTYPE html>
<html>
  <head>
    <title>Testing super-cookies</title>
    <meta charset="utf8"/>
    <link id="favicon" rel="shortcut icon" type="image/png" href="" />
  </head>
  <body>
    <script src="./post_data.js"></script>
    <script>
    const sleep = async (t) => new Promise(resolve => window.setTimeout(resolve, t));
     (async () => {
       try {
      const iframe_root_same = "https://test-pages.privacytests2.org";
      const param = (key) => new URLSearchParams(window.location.search).get(key);
      const mode = param("mode");
      const me = param("me");
      const thirdparty = param("thirdparty");
      const sessionId = param("sessionId");
      console.log({mode, me, thirdparty, sessionId});
      let favicon = document.getElementById("favicon");
      const baseURI = "https://test-pages.privacytests2.org/live";
      favicon.setAttribute("href", `${baseURI}/resource?type=favicon&key=${sessionId}`);
      const listener = async (event) => {
        if (!event.origin.includes("privacytests")) {
          return;
        }
        const data = JSON.parse(event.data);
        if (data.command === "disableDarkMode" || data.command === "enableDarkMode") {
          return;
        }
        removeEventListener("message", listener);
        showData("origin", event.origin);
        document.body.setAttribute("data-test-results", event.data);
        const category = `supercookies_${mode}_${thirdparty}`;
        if (mode === "read") {
          // document.body.style.backgroundColor = "green";
          await postDataAndCarryOn(data, category);
          // document.body.style.backgroundColor = "red";
        } else {
          if (!me) {
            document.documentElement.addEventListener("click", () => {
              window.open(`${iframe_root_same}/supercookies.html?mode=read&thirdparty=same&sessionId=${sessionId}`, "_blank", "noopener");
            });
          }
          await postData(data, category);
        }
      };
      addEventListener("message", listener);
      if (mode === "read" && me === "true" && thirdparty === "same") {
        while (true) {
          let response = await fetch(`https://results.privacytests.org/step?sessionId=${sessionId}`, { cache: "no-store"});
          let {step} = await response.json();
          if (step > 0) {
            break;
          }
          await sleep(1000);
        }
      }
      let iframe = document.createElement("iframe");
      iframe.height="1000px"
      document.body.appendChild(iframe);
      iframe_root = (location.hostname === "localhost" ||
                    location.hostname === "127.0.0.1" ||
                    location.hostname === "")
                  ? "" : "https://test-pages.privacytests2.org/";
      iframe.src = `${iframe_root}/supercookies_inner.html${window.location.search}`;
         iframe.allow = "geolocation camera microphone";
       } catch (e) {
         showError(e);
       }
    })();
    </script>
  </body>
</html>
